import a2b from '../utils/str2hex2ab'
let deviceId = '', // 设备id
  serviceId = '', // 服务id 
  readCharacteristicId = '', // 可读id
  writeCharacteristicId = '', // 可写id
  notifyCharacteristicId = '', //notify特性id
  devicesList = [],
  deviceName = 'LSSZKZQ'

// 初始化蓝牙模块。iOS 上开启主机/从机（外围设备）模式时需分别调用一次，并指定对应的 mode
let openBluetoothAdapter = () => {
  return new Promise((resolve, reject) => {
    wx.openBluetoothAdapter({
      // mode:'peripheral', // 'peripheral' || 'central'
      success(res) {
        resolve({
          ok: true,
          errCode: res.errCode,
          errMsg: errcode(res.errCode)
        })
      },
      fail(res) {
        resolve({
          ok: false
        })
        wx.showModal({
          title: `错误代码：${res.errCode}`,
          content: errcode(res.errCode),
          showCancel: false,
          confirmText: '好的'
        })
      }
    })
  })
}

// 关闭蓝牙模块。调用该方法将断开所有已建立的连接并释放系统资源
let closeBluetoothAdapter = () => {
  return new Promise((resolve, reject) => {
    wx.closeBluetoothAdapter({
      success(res) {
        resolve({
          ok: true,
          errCode: res.errCode,
          errMsg: errcode(res.errCode)
        })
        devicesList = []
      },
      fail(res) {
        resolve({
          ok: false
        })
        wx.showModal({
          title: `错误代码：${res.errCode}`,
          content: errcode(res.errCode),
          showCancel: false,
          confirmText: '好的'
        })
      }
    })
  })
}

// 获取本机蓝牙适配器状态
let getBluetoothAdapterState = () => {
  return new Promise((resolve, reject) => {
    wx.getBluetoothAdapterState({
      success(res) {
        // 蓝牙适配器是否可用
        if (res.available) {
          resolve({
            ok: true,
            errCode: res.errCode,
            errMsg: errcode(res.errCode)
          })
        } else {
          wx.showModal({
            title: `错误代码：${res.errCode}`,
            content: errcode(res.errCode),
            showCancel: false,
            confirmText: '好的'
          })
        }
      },
      fail(res) {
        resolve({
          ok: false
        })
        wx.showModal({
          title: `错误代码：${res.errCode}`,
          content: errcode(res.errCode),
          showCancel: false,
          confirmText: '好的'
        })
      }
    })
  })
}


let startBluetoothDevicesDiscovery = (cb) => {
  // 监听搜索到新设备的事件
  wx.onBluetoothDeviceFound((res) => {
    let name = res.devices[0].name ? res.devices[0].name : res.devices[0].localName
    if (name != deviceName) return
    for (const item of devicesList) {
      // 设备id相同
      if (item.deviceId == res.devices[0].deviceId) {
        //更新当前蓝牙设备的信号强度，单位 dBm
        item.rssi = res.devices[0].RSSI
        cb(devicesList)
        return
      }
    }
    devicesList.push({
      name: deviceName,
      rssi: res.devices[0].RSSI,
      deviceId: res.devices[0].deviceId,
      connectable: res.devices[0].connectable,
      advertisServiceUUIDs: res.devices[0].advertisServiceUUIDs
    })
    cb(devicesList)
  })
  // 开始搜寻附近的蓝牙外围设备。此操作比较耗费系统资源
  wx.startBluetoothDevicesDiscovery({
    // services: ['FEE7'], // 只搜索主服务 UUID 为 FEE7 的设备
    allowDuplicatesKey: true,
    success(msg) {
      console.log(msg)
      // 监听搜索到新设备的事件
    },
    fail(res) {
      console.error(res)
    }
  })
}

// 停止搜寻附近的蓝牙外围设备
let stopBluetoothDevicesDiscovery = () => {
  return new Promise((resolve, reject) => {
    wx.stopBluetoothDevicesDiscovery({
      success(res) {
        resolve({
          ok: true,
          errCode: res.errCode,
          errMsg: errcode(res.errCode)
        })
      },
      fail(res) {
        resolve({
          ok: false
        })
        wx.showModal({
          title: `错误代码：${res.errCode}`,
          content: errcode(res.errCode),
          showCancel: false,
          confirmText: '好的'
        })
      }
    })
  })
}

// 根据指定 deviceId 连接蓝牙低功耗设备
let createBLEConnection = (id) => {
  return new Promise((resolve, reject) => {
    console.log(id)
    deviceId = id
    wx.createBLEConnection({
      deviceId,
      success(res) {
        resolve({
          ok: true,
          errCode: res.errCode,
          errMsg: errcode(res.errCode)
        })
      },
      fail(res) {
        resolve({
          ok: false
        })
        wx.showModal({
          title: `错误代码：${res.errCode}`,
          content: errcode(res.errCode),
          showCancel: false,
          confirmText: '好的'
        })
      }
    })
  })
}
// 断开与蓝牙低功耗设备的连接
let closeBLEConnection = () => {
  return new Promise((resolve, reject) => {
    wx.closeBLEConnection({
      deviceId,
      success(res) {
        wx.hideLoading()
        resolve({
          ok: true,
          errCode: res.errCode,
          errMsg: errcode(res.errCode)
        })
      },
      fail(res) {
        resolve({
          ok: false
        })
        wx.hideLoading()
        wx.showModal({
          title: `错误代码：${res.errCode}`,
          content: errcode(res.errCode),
          showCancel: false,
          confirmText: '好的'
        })
      }
    })
  })
}

// 监听蓝牙低功耗连接状态的改变事件
let onBLEConnectionStateChange = (cb) => {
  wx.onBLEConnectionStateChange((res) => {
    console.log('蓝牙连接状态发生改变', res)
    cb(res)
    // if (!res.connected) {
    //   devicesList = []
    //   wx.showToast({
    //     title: '蓝牙连接已断开',
    //     icon: 'error'
    //   })
    // }
  })
}

// 获取蓝牙低功耗指定id设备所有服务 (service)
let getBLEDeviceServices = () => {
  return new Promise((resolve, reject) => {
    wx.getBLEDeviceServices({
      deviceId,
      success(res) {
        console.log('该设备的所有services：', res.services)
        serviceId = "6E40FF00-B5A3-F393-E0A9-E50E24DCCA9E"
        getBLEDeviceCharacteristics()
      },
      fail(res) {
        resolve({
          ok: false
        })
        wx.showModal({
          title: `错误代码：${res.errCode}`,
          content: errcode(res.errCode),
          showCancel: false,
          confirmText: '好的'
        })
      }
    })
  })
}

// 获取蓝牙低功耗设备某个服务中所有特征 (characteristic)
let getBLEDeviceCharacteristics = () => {
  readCharacteristicId = ''
  writeCharacteristicId = ''
  notifyCharacteristicId = ''
  return new Promise((resolve, reject) => {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success(res) {
        console.log(res.characteristics)
        for (const item of res.characteristics) {
          // console.log('服务中所有特征uuid：' + item.uuid)
          // 该特征是否支持 read 操作
          if (item.properties.read) {
            readCharacteristicId = item.uuid
            console.log('可读id：', readCharacteristicId)
            readBLECharacteristicValue()
          }
          // 该特征是否支持 write 操作
          if (item.properties.write) {
            writeCharacteristicId = item.uuid // 蓝牙设备特征的 UUID
            console.log('可写id：', writeCharacteristicId)
          }
          // 该特征是否支持 notify 操作 || 该特征是否支持 indicate 操作
          if (item.properties.notify || item.properties.indicate) {
            notifyCharacteristicId = item.uuid
            console.log('可监听id：', notifyCharacteristicId)
            notifyBLECharacteristicValueChange()
          }

        }
      },
      fail(res) {
        resolve({
          ok: false
        })
        wx.showModal({
          title: `错误代码：${res.errCode}`,
          content: errcode(res.errCode),
          showCancel: false,
          confirmText: '好的'
        })
      }
    })
  })
}
// 启用蓝牙低功耗设备特征值变化时的 notify 功能
let notifyBLECharacteristicValueChange = () => {
  wx.notifyBLECharacteristicValueChange({
    characteristicId: notifyCharacteristicId,
    deviceId,
    serviceId,
    state: true,
    success(res) {
      console.log('启用notify成功');
      // 监听蓝牙低功耗设备的特征值变化事件
      wx.onBLECharacteristicValueChange((msg) => {
        console.log(`接收到蓝牙返回数据：\n特性值 ${msg.characteristicId}发生改变\n转换为16进制后：${a2b.ab2hex(msg.value)}\n转换为字符串后：${a2b.ab2str(msg.value)}`)
      })

    },
    fail(res) {
      console.log('启用notify失败')
      wx.showModal({
        title: `错误代码：${res.errCode}`,
        content: errcode(res.errCode),
        showCancel: false,
        confirmText: '好的'
      })
    }
  })
}
// 读取蓝牙低功耗设备特征值的二进制数据
let readBLECharacteristicValue = () => {
  wx.readBLECharacteristicValue({
    deviceId,
    serviceId,
    characteristicId: readCharacteristicId,
    success(res) {
      console.log('读取特征值的二进制数据success:', res)
    }
  })
}

// 向蓝牙低功耗设备特征值中分包写入 字符串
let writeString = async (value) => {
  let buffer = a2b.str2ab(value)
  let pos = 0
  let bytes = buffer.byteLength // 只读。ArrayBuffer的长度（字节）。
  let result = ''
  console.log('bytes：' + bytes + '\nbuffer：' + buffer)
  while (bytes > 0) {
    console.log('此时bytes值：', bytes)
    let temBuffer;
    if (bytes > 20) {
      temBuffer = buffer.slice(pos, pos + 20)
      pos += 20
      bytes -= 20
      let res = await write(temBuffer)
      console.log("开始发送", res)
      sleep(0.02)
    } else {
      temBuffer = buffer.slice(pos, pos + bytes)
      pos += bytes
      bytes -= bytes
      let res = await write(temBuffer)
      console.log("最后发送", res)
      sleep(0.02)
    }
  }

}

// 向蓝牙低功耗设备特征值中写入 规定指令
let writePrescriptiveDirective = async (value) => {
  let buffer = new ArrayBuffer(value.length)
  let dataView = new DataView(buffer)
  value.forEach((item, index) => {
    dataView.setUint8(index, item)
  });
  console.log("dataView:",dataView)
  let res = await write(buffer)
  return res
}

// 向蓝牙低功耗设备特征值中写入 处理好的数据
let write = (value) => {
  return new Promise((resolve, reject) => {
    console.log("writeCharacteristicId:",writeCharacteristicId)
    console.log("deviceId:",deviceId)
    console.log("serviceId:",serviceId)
    console.log("value:",value)
    wx.writeBLECharacteristicValue({
      characteristicId: writeCharacteristicId,
      deviceId,
      serviceId,
      value: value,
      success(res) {
        console.log('发送成功')
        resolve({
          ok: true,
          errCode: res.errCode,
          errMsg: errcode(res.errCode)
        })
      },
      fail(res) {
        console.log('发送失败')
        resolve({
          ok: false,
          errCode: res.errCode,
          errMsg: errcode(res.errCode)
        })
        // wx.showModal({
        //   title: `错误代码：${res.errCode}`,
        //   content: errcode(res.errCode),
        //   showCancel: false,
        //   confirmText: '好的'
        // })
      }
    })
  })
}
// 延时
function sleep(delay) {
  var start = (new Date()).getTime();
  while ((new Date()).getTime() - start < delay) {
    continue;
  }
}
// 错误码
function errcode(code) {
  let errcode = [{
    code: 0,
    msg: '操作成功'
  }, {
    code: -1,
    msg: '已连接'
  }, {
    code: 10000,
    msg: '未初始化蓝牙适配器'
  }, {
    code: 10001,
    msg: '当前蓝牙适配器不可用'
  }, {
    code: 10002,
    msg: '未找到指定设备'
  }, {
    code: 10003,
    msg: '连接失败'
  }, {
    code: 10004,
    msg: '未找到指定服务'
  }, {
    code: 10005,
    msg: '未找到指定特征'
  }, {
    code: 10006,
    msg: '当前连接已断开'
  }, {
    code: 10007,
    msg: '当前特征不支持此操作'
  }, {
    code: 10008,
    msg: '未知错误'
  }, {
    code: 10009,
    msg: 'Android系统版本过低'
  }, {
    code: 10012,
    msg: '连接超时'
  }, {
    code: 10013,
    msg: '设备id为空或者格式不正确'
  }]
  for (const item of errcode) {
    if (code === item.code) {
      return item.msg
    }
  }
}

module.exports = {
  openBluetoothAdapter,
  closeBluetoothAdapter,
  getBluetoothAdapterState,
  startBluetoothDevicesDiscovery,
  stopBluetoothDevicesDiscovery,
  createBLEConnection,
  closeBLEConnection,
  onBLEConnectionStateChange,
  getBLEDeviceServices,
  writeString,
  writePrescriptiveDirective,
  notifyBLECharacteristicValueChange
}